import * as THREE from '../../../../modules/three/three.module.js'
import { flatten } from '../util/StaticMethods.js';

let count = 0;

// 固定视角 网格
export default class EyeIndicator extends THREE.Group {
  eyeMesh;
  focus = new THREE.Vector3(0, 0, 0);
  // 眼睛朝向的单位向量
  eyeFacing = new THREE.Vector3(0, 0, 0);
  dataObj = { pos: new THREE.Vector3(), focus: new THREE.Vector3() };
  geometryInfo;

  constructor() {
    super();
    this.dataObj.id = count++;
    const width = 0.6;
    const height = 0.3;
    const deep = 0.6;
    const gap = 0.02;
    const upArrowWidth = 0.5;
    const upArrowHeight = 0.25;
    const hh = height * 0.5;
    const hw = width * 0.5;

    // 初始化顶点
    const a0 = new THREE.Vector3(0, 0, 0);
    const a1 = new THREE.Vector3(-hw, hh, deep);
    const a2 = new THREE.Vector3(hw, hh, deep);
    const a3 = new THREE.Vector3(hw, -hh, deep);
    const a4 = new THREE.Vector3(-hw, -hh, deep);
    const b0 = new THREE.Vector3(0, hh + gap + upArrowHeight, deep);
    const b1 = new THREE.Vector3(-0.5 * upArrowWidth, hh + gap, deep);
    const b2 = new THREE.Vector3(0.5 * upArrowWidth, hh + gap, deep);

    const lineVectors = [a0, a1, a2, a3, a4, b0, b1, b2];
    const lineIndex = [
      0, 1, 0, 2, 0, 3, 0, 4, 1, 2, 2, 3, 3, 4, 4, 1, 5, 6, 6, 7, 7, 5,
    ];
    const lineGeo = new THREE.BufferGeometry();
    lineGeo.setIndex(lineIndex);
    lineGeo.setAttribute(
      'position',
      new THREE.BufferAttribute(flatten(lineVectors), 3),
    );
    const lineSegments = new THREE.LineSegments(
      lineGeo,
      new THREE.LineBasicMaterial({ color: '#a20a24', toneMapped: false }),
    );

    const index = [
      0, 2, 1, 0, 3, 2, 0, 4, 3, 0, 1, 4, 1, 2, 3, 1, 3, 4, 6, 5, 7,
    ];
    const geometry = new THREE.BufferGeometry();
    geometry.setIndex(index);
    geometry.setAttribute(
      'position',
      new THREE.BufferAttribute(flatten(lineVectors), 3),
    );
    const mesh = new THREE.Mesh(
      geometry,
      new THREE.MeshBasicMaterial({
        color: '#0089bb',
        transparent: true,
        opacity: 0.5,
      }),
    );
    mesh.visible = false;
    this.eyeMesh = mesh;
    this.add(mesh);
    this.add(lineSegments);
    this.geometryInfo = { index, vectors: lineVectors };
  }

  setFocus(focus) {
    this.focus.copy(focus);
    this.lookAt(focus.x, focus.y, focus.z);
    this.eyeFacing.copy(this.focus).sub(this.position).normalize();
  }

  getDist() {
    return this.position.distanceTo(this.focus);
  }

  getDataObj() {
    this.dataObj.pos.copy(this.position);
    this.dataObj.focus.copy(this.focus);
    return this.dataObj;
  }
}
